//
//  PostCodeHelper.m
//  PostCode4JPApp
//
//  Created by Tonny Xu on 7/27/10.
//  Copyright 2010 CLiA Inc. All rights reserved.
//

#import "PostCodeHelper.h"
#import "DOPostCode.h"
#import "SLDBAccess.h"

@implementation PostCodeHelper

+(NSArray *)getDataFromPostCode:(NSString *)postCode{
    static const char* sql = "select * from postcode where postcode like ?";
    
    static sqlite3_stmt *stmt = nil;
    if (nil == stmt) {
        if (sqlite3_prepare_v2([SLDBAccess sharedSLDBAccess].database,sql,-1,&stmt,NULL) != SQLITE_OK) 
        {
            NSAssert1(NO, @"Init prepared statement failed with error: %s", sqlite3_errmsg([SLDBAccess sharedSLDBAccess].database));
            abort();
        }
    }
    
    sqlite3_bind_text(stmt, 1, [postCode UTF8String], -1, SQLITE_TRANSIENT);
    
    NSMutableArray *result = [NSMutableArray array];
    
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        DOPostCode *aPostcode = [[DOPostCode alloc] init];
        
        aPostcode.postcodeId    = [NSNumber numberWithInt:sqlite3_column_int(stmt, 0)];
        aPostcode.header        = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 1)];
        aPostcode.postcode      = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 2)];
        aPostcode.pref_half     = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 3)];
        aPostcode.district_half = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 4)];
        aPostcode.street_half   = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 5)];
        aPostcode.pref_full     = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 6)];
        aPostcode.district_full = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 7)];
        aPostcode.street_full   = [SLDBAccess getSafeNSStringFromCString:sqlite3_column_text(stmt, 8)];
        
        [result addObject:aPostcode];
        [aPostcode release];
    }
    sqlite3_reset(stmt);
    
    return result;
    
}

@end
